package org.itboys.mobile.service.mongo.web;

import org.apache.commons.collections.map.HashedMap;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.mobile.entity.mongo.SundayFindProduct;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.SundayProduct;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Auther: 罗尧坤
 * Date: 2018/7/24
 * Description:
 */
@Service
public class SundayFindProductService extends BaseMongoService<SundayFindProduct> {

    @Autowired
    private SundayMemberService memberService;

    @Resource(name = "mobileDs")
    private MongoDataSource kitchenDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return kitchenDataSource;
    }
    @Override
    protected Class<SundayFindProduct> getEntityClass() {
        return SundayFindProduct.class;
    }

    /**
     * 分页查询帮我找房搜查条件
     * @param request
     * @return
     */
    public PageResult<SundayFindProduct> select(HttpServletRequest request){
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request);
        param.put("isDeleted", 0);

        PageResult<SundayFindProduct> result = super.pageQuery(request, param);

        List<SundayFindProduct> data = result.getData();
        if(ListUtil.isNull(data)){
            return result;
        }

        //获取用户id列表
        List<Long> memberIds=new ArrayList<>();
        for (SundayFindProduct findProduct :data) {
            memberIds.add(findProduct.getMemberId());
        }
        Map<String,Object> _param=new HashedMap();

        //传入条件
        _param.put("isDeleted", 0);
        _param.put("id in",memberIds);
        List<SundayMember> members = memberService.list(param);
        //匹配用户id和找房的用户id, 赋值

        for (SundayFindProduct findProduct :data) {
            for (SundayMember member:members) {
                if (findProduct.getMemberId().equals(member.getId())){
                    findProduct.setMemberName(member.getNickName());
                    break;
                }
            }

            //异常处理

            if (findProduct.getMemberName()==null){
                findProduct.setMemberName("找不到对应用户名");
            }
        }
        result.setTotal(result.getTotal());
        result.setData(data);
        return result;
    }

    /**
     * 设置是否已回执用户
     * @param id
     * @param status
     */
    public void setStatus(Long id,Integer status){
        super.update(id,"status",status);
    }

}
